#!/usr/bin/perl
use strict;
use warnings;

our %cfg;
our %simcfg;
require "./eeprom_init.cfg";
my $indent = 30;
printf "#include <system.h>\n\n";
if(keys(%simcfg)) {
    printf "#ifndef SIMULATOR\n";
    print_config(\%cfg);
    printf "#else\n";
    print_config(\%simcfg);
    printf "#endif\n";
} else {
    print_config(\%cfg);
}

sub print_config {
    my($cfg) = @_;
    printf "#pragma DATA _EEPROM,\n";
    printf "%${indent}s,    /* width of LCD    : %8d */ \\\n", as_hex8($cfg->{lcd_width}), $cfg->{lcd_width};
    printf "%${indent}s,    /* height of LCD   : %8d */ \\\n", as_hex8($cfg->{lcd_height}), $cfg->{lcd_height};
    printf "%${indent}s,    /* number of Kegs  : %8d */ \\\n", as_hex8($cfg->{num_kegs}), $cfg->{num_kegs};
    printf "%${indent}s,    /* timeout         : %8d */ \\\n", as_hex8($cfg->{timeout}), $cfg->{timeout};
    for (my $i = 0; $i < 8; $i++) {
        $cfg->{"keg_$i"} = $cfg->{"keg_" . ($i-1)} if (! $cfg->{"keg_$i"});
        my $data = $cfg->{"keg_$i"};
        printf "%${indent}s     /********** Keg # $i ***********/ \\\n", "";
        printf "%${indent}s,    /* keg full value  : %8d */ \\\n", as_hex24($data->{keg_full}), $data->{keg_full};
        printf "%${indent}s,    /* hz per pint     : %8d */ \\\n", as_hex24($data->{hz_per_pint}), $data->{hz_per_pint};
        printf "%${indent}s,    /* max pints       : %8d */ \\\n", as_hex8($data->{max_pints}), $data->{max_pints};
    }
    for (my $i = 0; $i < 8; $i++) {
        my $data = $cfg->{"keg_$i"};
        my $len = 17; #$cfg->{lcd_width} - 2;
        my $str = substr($data->{name}, 0, $len);
        while(length($str) < $len) {
            $str .= " ";
        }
        printf "%${indent}s,    /* keg %d name                 */ \\\n", as_text($str), $i;
    }
    printf "%${indent}s\n", "0x00";
}
  

sub as_hex8 {
    my($val) = @_;
    return sprintf("0x%02X", $val);
}

sub as_hex24 {
    my($val) = @_;
    return sprintf("0x%02X, 0x%02X, 0x%02X", 0xff & $val, 0xff & ($val >> 8), 0xff & ($val >> 16));
}


sub as_hex32 {
    my($val) = @_;
    return sprintf("0x%02X, 0x%02X, 0x%02X, 0x%02X", 0xff & $val, 0xff & ($val >> 8), 0xff & ($val >> 16), $val >> 24);
}

sub as_text {
    my($val) = @_;
    return sprintf("\"%s\"", $val);
}
